package models

import (
	"fmt"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 工作流 审批流
type WorkOrderTemplate struct {
	Model        // 不用每次写ID 和 createAt了
	Name  string `json:"name" validate:"required,min=1,max=50" gorm:"uniqueIndex;type:varchar(100);comment:工单模板名称，支持使用通配符*进行模糊搜索" `
	//Creator User   `json:"Creator" `
	UserID uint
	// 需要关联2个对象 审批流  表单设计
	FormDesignID uint `json:"formDesignID"`
	ProcessID    uint `json:"processID"`

	Process    *Process    `json:"process" gorm:"-"`
	FormDesign *FormDesign `json:"formDesign" gorm:"-"`

	Key            string `json:"key" gorm:"-"` //给前端表格
	CreateUserName string `json:"createUserName" gorm:"-"`
	ProcessName    string `json:"processName" gorm:"-"`
	FormDesignName string `json:"formDesignName" gorm:"-"`
}

func (obj *WorkOrderTemplate) Create() error {
	return Db.Create(obj).Error

}
func (obj *WorkOrderTemplate) DeleteOne() error {

	return Db.Select(clause.Associations).Unscoped().Delete(obj).Error

}

func DeleteWorkOrderTemplateOneByInstanceId(iid string) error {

	return Db.Select(clause.Associations).Unscoped().Where("instance_id = ?", iid).Delete(&WorkOrderTemplate{}).Error
}

func (obj *WorkOrderTemplate) CreateOne() error {
	return Db.Create(obj).Error

}

func (obj *WorkOrderTemplate) UpdateOne() error {
	return Db.Where("id = ?", obj.ID).Updates(obj).Error

}

func (obj *WorkOrderTemplate) UpdateFlowNodes(nodes []FlowNode) error {

	return Db.Model(obj).Association("FlowNodes").Replace(nodes)

}

func (obj *WorkOrderTemplate) FillFrontAllData() {
	dbUser, _ := GetUserById(int(obj.UserID))
	if dbUser != nil {
		obj.CreateUserName = dbUser.Username
	}

	dbProcess, _ := GetProcessById(int(obj.ProcessID))

	if dbProcess != nil {
		dbProcess.FillFrontAllData()
		obj.ProcessName = dbProcess.Name
		obj.Process = dbProcess
	}

	dbFormDesign, _ := GetFormDesignById(int(obj.ProcessID))
	obj.FormDesign = dbFormDesign
	if dbFormDesign != nil {
		obj.FormDesignName = dbFormDesign.Name
	}

	obj.Key = fmt.Sprintf("%d", obj.ID)

}
func GetWorkOrderTemplateAll() (objs []*WorkOrderTemplate, err error) {
	err = Db.Find(&objs).Error
	return
}

func GetWorkOrderTemplateByLevel(level int) (objs []*WorkOrderTemplate, err error) {
	err = Db.Where("level = ?", level).Preload("OpsAdmins").Find(&objs).Error
	return
}

// select * from ecs where
func GetWorkOrderTemplateByIdsWithLimitOffset(ids []int, limit, offset int) (objs []*WorkOrderTemplate, err error) {
	err = Db.Limit(limit).Offset(offset).Find(&objs, ids).Error
	return
}

func GetWorkOrderTemplateByInstanceId(instanceId string) (*WorkOrderTemplate, error) {

	var dbObj WorkOrderTemplate
	err := Db.Where("instance_id = ?", instanceId).Preload("FlowNodes").First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("WorkOrderTemplate不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetWorkOrderTemplateById(id int) (*WorkOrderTemplate, error) {

	var dbObj WorkOrderTemplate
	err := Db.Where("id = ?", id).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("WorkOrderTemplate不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetWorkOrderTemplateByFormDesignId(formDesignId int) (*WorkOrderTemplate, error) {

	var dbObj WorkOrderTemplate
	err := Db.Where("form_design_id = ?", formDesignId).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("WorkOrderTemplate不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}

func GetWorkOrderTemplateByProcessId(processId int) (*WorkOrderTemplate, error) {

	var dbObj WorkOrderTemplate
	err := Db.Where("process_id = ?", processId).First(&dbObj).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("WorkOrderTemplate不存在")
		}
		return nil, fmt.Errorf("数据库错误:%w", err)
	}
	return &dbObj, nil

}
